package main

import (
	"fmt"
	"github.com/julienschmidt/httprouter"
	"io/ioutil"
	"log"
	"net/http"
)

func HelloWorld(w http.ResponseWriter, r *http.Request, param httprouter.Params) {
	fmt.Println(r.Header)
	fmt.Println(r.Header["Cookie"])

	len := r.ContentLength
	body := make([]byte, len)
	r.Body.Read(body)
	fmt.Println(string(body))
	fmt.Fprintf(w, "hello %s", param.ByName("name"))
}

func getBody(w http.ResponseWriter, r *http.Request, param httprouter.Params) {
	len := r.ContentLength
	body := make([]byte, len)
	r.Body.Read(body)
	fmt.Println(string(body))
	fmt.Fprintf(w, "hello %s", param.ByName("name"))
}

func getForm(w http.ResponseWriter, r *http.Request, param httprouter.Params) {
	//ParseForm对语法进行分析
	r.ParseForm()
	//Form获取表单值和URL的值
	fmt.Fprintln(w, r.Form)
	//PostForm只获取Form表单的值
	fmt.Fprintln(w, r.PostForm)
	//获取multipart/form-data编码的表单数据，需要从新分析语法
	r.ParseMultipartForm(1024)
	fmt.Fprintln(w, r.MultipartForm)

	//获取指定的值
	//FormValue 在给定键值有多个值的情况下，也只会从Form结构中取出给定的第一个值
	fmt.Fprintln(w, r.FormValue("hello"))
	//PostFormValue只能取Form里边的值
	fmt.Fprintln(w, r.PostFormValue("hello"))
}

func upload(w http.ResponseWriter, r *http.Request, param httprouter.Params)  {
	file, _, err := r.FormFile("pic")
	if err == nil {
		data, err := ioutil.ReadAll(file)
		if err == nil {
			fmt.Fprintln(w, string(data))
		} else {
			log.Println(55)
			fmt.Fprintln(w, err)
		}
	} else {
		log.Println(59)
		fmt.Fprintln(w, err)
	}
}

func main() {
	//创建多路复用器
	mux := httprouter.New()
	mux.GET("/hello/:name", HelloWorld)
	mux.POST("/getBody/", getBody)
	mux.POST("/getForm/", getForm)
	mux.POST("/upload/", upload)

	server := http.Server{
		Addr:              "127.0.0.1:8080",
		Handler:           mux,
	}
	server.ListenAndServe()
}
